/****************************************************************************
 * 2023.11 超萌大脑斧
 ****************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
using QFramework;

namespace QFramework.Example
{
	public partial class CoinUpgradePanel : UIElement,IController
	{
		
		private void Awake()
		{
			//CoinText.text = "金币："+Global.Coin.Value;
			
			CoinUpgradeItemTemple.Hide();
			
			BtnClose.onClick.AddListener(() =>
			{
				this.Hide();
			});
			
			// 遍历所有需要生成的按钮信息，要判断item是否已经升级，未升级的才会显示
			foreach (var item in this.GetSystem<CoinUpgradeSystem>().Items.Where(item=>!item.UpgradeFinish))
			{
				CoinUpgradeItemTemple.InstantiateWithParent(CoinUpgradeItemRoot)
					.Self(self =>
					{
						var itemCache = item; //要做缓存，不然最后（itemCache.Upgrade()）调用的事件就是遍历最后一个按钮的事件了
						//print(self.name);
						self.GetComponentInChildren<Text>().text = itemCache.Description + $"---{itemCache.Price} 金币";
						self.onClick.AddListener(() =>
						{
							itemCache.Upgrade();
							AudioKit.PlaySound("ability_level_up");
						});

						var selfCache = self;
						item.OnChange.Register(() =>
						{
							if (itemCache.ConditionCheck())
							{
								selfCache.Show();
							}
							else
							{
								selfCache.Hide();
							}
						}).UnRegisterWhenGameObjectDestroyed(selfCache);

						if (itemCache.ConditionCheck())
						{
							selfCache.Show();
						}
						else
						{
							selfCache.Hide();
						}
						// 只有当金币数大于5时才会显示升级按钮
						Global.Coin.RegisterWithInitValue(coin =>
						{
							CoinText.text = "金币:" + coin;
							if (coin >= itemCache.Price)
							{
								selfCache.interactable = true; //true是激活，false则是不激活，无法点击
							}
							else
							{
								selfCache.interactable = false;
							}
						}).UnRegisterWhenGameObjectDestroyed(self);
					});
			}
		}

		protected override void OnBeforeDestroy()
		{
		}

		public IArchitecture GetArchitecture()
		{
			return Global.Interface;
		}
	}
}